var express = require('express');
var router = express.Router();
var {movie_model,user_model} = require("../utils/model")
var {aesDecrypt} = require("../utils")
/* GET home page. */
// 接口  
// get get请求
// /  接口地址
// req 请求 (req.url req.query req.body req.params req.hash )
// res 响应 (res.write res.send  res.json )  响应数据给客户端 
// next 进入下一个中间件 
// res.render 渲染一个模块  
router.get('/', function(req, res, next) {
  console.log(req.session)
  res.render('index',
   { 
    title: 'Express',
    username:req.session.username 
  });
});

router.get("/home",(req,res)=>{
   res.render("home",{
      msg:"2107-daydayup",
      count:8888,
      text:"马上毕业了,记得推荐学弟来-学妹来",
      tag:"<h2>Are YOu OK???</h2>",
      inp:"越努力越幸运 - 2107 ",
      flag:true,
      list:['拉拉',"莉莉","老王","大左","旭旭"]
   })
})
router.get("/logout",(req,res)=>{
  // 销毁session
   req.session.destroy(()=>{
      res.redirect("/")
   })
})

router.get("/list",(req,res)=>{
  movie_model.find({},{})
  .then(result=>{
    res.render("list",{
      result
    })
  })
})

router.get("/detail",(req,res)=>{
  movie_model.findOne({
    id:req.query.id 
  })
  .then(result=>{
      res.render("detail",{result})
  })
})

router.get("/chat",(req,res)=>{
  res.render("chat")
})

router.get("/login",(req,res)=>{
  var username = req.query.username ?  aesDecrypt(req.query.username) : ''
  res.render("login",{username})
})

router.get("/demo",(req,res)=>{
  res.send("Dmeo - Demo - 2107 学会写项目 ")
})

router.get("/test",(req,res)=>{
  res.send("<h2>this is main test interface</h2> ")
})

router.get("/data",(req,res)=>{
  res.json({
    code:200,
    msg:"请求成功",
    result:null,
    url:req.url,
    headers:req.headers,  // 请求头
    query:req.query,    // 查询参数  ? 拼接的search 参数 
  })
})

router.get("/good/:gid?",(req,res)=>{
   res.json({
     code:200,
     msg:"获取商品详情成功",
     params:req.params
   })
})  

router.post("/submit",(req,res)=>{
  res.json({
    code:200,
    msg:"提交成功",
    body:req.body  // post 提交的参数 
  })
})

router.all("/all",(req,res)=>{
  console.log(req.body)
  console.log(req.query)
   res.send("this is all method get && post ")
})

router.get("/register",(req,res)=>{
  res.render("register")
})


router.get("/movie",(req,res)=>{
  var limit = req.query.limit * 1 || 0; 
  movie_model.find({},{_id:0})
  .limit(limit)
  .sort({
    year:1
  })
  .then(result=>{
     res.json({
       code:200,
       msg:"获取电影列表成功",
       result
     })
  })
  .catch(err=>{
    res.json({
      code:500,
      msg:"服务器异常",
      err
    })
  })
})

router.get('/userlist',(req,res)=>{
  user_model.find({},{})
  .then(result=>{
    res.json({
      code:200,
      msg:"获取用户列表成功",
      result
    })
  })
  .catch(err=>{
    res.json({
      code:500,
      msg:"服务器异常",
      err
    })
  })
})

module.exports = router;
